package com.lineage.data.item_etcitem.doll;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Optional;
import java.util.Random;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.lineage.DatabaseFactory;
import com.lineage.data.cmd.CreateNewItem;
import com.lineage.data.executor.ItemExecutor;
import com.lineage.server.datatables.DollPowerTable;
import com.lineage.server.datatables.ItemPowerUpdateTable;
import com.lineage.server.datatables.ItemTable;
import com.lineage.server.model.L1Object;
import com.lineage.server.model.Instance.L1DollInstance;
import com.lineage.server.model.Instance.L1ItemInstance;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.model.doll.L1DollExecutor;
import com.lineage.server.model.doll.L1DollPowerSupper;
import com.lineage.server.serverpackets.S_ServerMessage;
import com.lineage.server.templates.L1Doll;
import com.lineage.server.templates.L1ItemPowerUpdate;
import com.lineage.server.utils.SQLUtil;



/**
 * 60219 魔法娃娃重生药剂
 * 随机生成魔法娃娃的技能
 * 
 */

public class DollReborn extends ItemExecutor{
	private static final Log _log = LogFactory.getLog(DollReborn.class);

	private static final HashMap<Integer, L1DollExecutor> _classList = L1DollPowerSupper.get().getClasslist();
	


//	private static final ArrayList<String> _checkList = new ArrayList<String>();
	private static final Random _random = new Random();
	private DollReborn() {
		// TODO Auto-generated constructor stub
	}
	


	public static DollReborn get() {
		return new DollReborn();
	}
	
	
	@Override
	public void execute(final int[] data, final L1PcInstance pc,
			final L1ItemInstance item) {
		try {
			// 对像OBJID
			final int targObjId = data[0];

			final L1ItemInstance tgItem = pc.getInventory().getItem(targObjId);

			if (tgItem == null) {
				return;
			}



			final L1Doll doll = DollPowerTable.get().get_type(tgItem.getItemId());
			if (doll == null) {
				// 2,477：只有魔法娃娃可以选择。
				pc.sendPackets(new S_ServerMessage(2477));
				return;
			}

			if (pc.getDoll(tgItem.getId()) != null) {
				// 1,181：这个魔法娃娃目前正在使用中。
				pc.sendPackets(new S_ServerMessage(1181));
				return;
			}
			if (pc.getDoll2(tgItem.getId()) != null) {
				// 1,181：这个魔法娃娃目前正在使用中。
				pc.sendPackets(new S_ServerMessage(1181));
				return;
			}
			
			// 删除卷轴
			pc.getInventory().removeItem(item, 1);
			
			pc.getInventory().removeItem(tgItem, 1);

			// 产生新物件			
			final L1ItemInstance tginfo_item = ItemTable.get().createItem(tgItem.getItemId());
			final L1Doll dollnew = DollPowerTable.get().get_type(tginfo_item.getItemId());
			int newTargObjId = tginfo_item.getId();
			reSetPowers(dollnew, newTargObjId, targObjId);
			if (tginfo_item != null) {
				tginfo_item.setIdentified(true);
				tginfo_item.setCount(1);
				pc.getInventory().storeItem(tginfo_item);
			}


			
			//试试看用checkItem能不能刷新
//			final L1Doll dollnew = doll;
//			
//			int newTargObjId = targObjId;
//			
//			reSetPowers(dollnew, newTargObjId, targObjId);
//			
//			pc.getInventory().checkItem(newTargObjId);
//			pc.getInventory().

			

			     
		


		} catch (final Exception e) {
			_log.error(e.getLocalizedMessage(), e);
		}
	}
	
	public void reSetPowers(L1Doll dollnew, int newTargetId ,final int targObjId ) {
		L1Doll _type = dollnew;
		try {
			
			int powerCount = _random.nextInt(6) + 3; // 生成一个3到8的随机整数
			String [] dollPowerSet1 = new String[powerCount];
			for (int i =0; i<dollPowerSet1.length; i++ ) {
				// 取一个数据库etcitem_doll_power中id的最大值，并取其中的随机值，由于有空缺，所以需要判断取出的ID是否可以用
//				int tmp = _random.nextInt(393) + 1 ;
				//判断这个id是否存在于表中
//				if(DollPowerTable.get().get_classList().containsValue(tmp)){
					dollPowerSet1[i] = "" + ( _random.nextInt(393) + 1 );
//				}
			}
			boolean iserr = false;
			ArrayList<L1DollExecutor> powerList = new ArrayList<L1DollExecutor>();
			if ( dollPowerSet1.length > 0 ) {
				for (String string : dollPowerSet1) {
					L1DollExecutor e = (L1DollExecutor) _classList.get(Integer.valueOf(Integer.parseInt(string)));

					if (e != null) {
						//这里添加娃娃的能力值
						
						//处理相同属性的能力值重复的问题
						
					
						powerList.add(e);
						
					} else {
						_log.error("娃娃能力取回错误-没有这个编号,是这里么:" + string);
						iserr = true;
					}
				}
			}
			_type.setPowerList(powerList);	
			
			writeDPStable(newTargetId, targObjId, dollPowerSet1);
		} catch (Exception e) {
			_log.error(e.getLocalizedMessage(), e);
		}
	}
	



	
	public void writeDPStable(int newTargetId, final int targObjId,  String [] dollPowerSet ) {
		
		String [] dollPowerSet2 = dollPowerSet;
		String s = "";
		for (String string : dollPowerSet2) {
			s = string + "," + s;
		}
		
		runInsert(newTargetId, s);
		
		runDelete(targObjId);

//		Connection cn = null;
//		PreparedStatement ps = null;
//		ResultSet rs = null;
//		try {
//			cn = DatabaseFactory.get().getConnection();
//			ps = cn.prepareStatement("select id from `doll_power_supper`");
//			rs = ps.executeQuery();
//			boolean b = false;
//			while (rs.next()) {
//				int id = rs.getInt("id");
//				if (id == targObjId) {
//					b = true;
//				}					
//			}
//			if ( b == true ) {
//				runUpdate(targObjId, s);
//			}else {
//				runInsert(targObjId, s);
//			}
//		} catch (Exception e) {
//			_log.error(e.getLocalizedMessage(), e);
//		}finally {
//			SQLUtil.close(rs);
//			SQLUtil.close(ps);
//			SQLUtil.close(cn);
//		}
	}
	
	private void runUpdate(final int targObjId, String s) {
		Connection cn = null;
		PreparedStatement ps = null;
		try {
			cn = DatabaseFactory.get().getConnection();
			ps = cn.prepareStatement("UPDATE `doll_power_supper` SET powers=? WHERE `id`=?");
			ps.setString(1, s);
			ps.setInt(2, targObjId);
			ps.execute();
		} catch (Exception e) {
			_log.error(e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(ps);
			SQLUtil.close(cn);
		}
	}
	
	private void runInsert(final int newTargetId, String s) {
		Connection cn = null;
		PreparedStatement ps = null;
		try {
			cn = DatabaseFactory.get().getConnection();
			ps = cn.prepareStatement("INSERT INTO `doll_power_supper` SET id=?, powers =?");
			ps.setInt(1, newTargetId);
			ps.setString(2, s);
			ps.execute();
		} catch (Exception e) {
			_log.error(e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(ps);
			SQLUtil.close(cn);

		}
	}
	
	private void runDelete(final int targObjId) {
		Connection cn = null;
		PreparedStatement ps = null;
		try {
			cn = DatabaseFactory.get().getConnection();
			ps = cn.prepareStatement("Delete from `doll_power_supper` WHERE `id`=?");
			ps.setInt(1, targObjId);
			ps.execute();
		} catch (Exception e) {
			_log.error(e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(ps);
			SQLUtil.close(cn);

		}
	}



	@Override
	public void execute(L1PcInstance pc) {
		// TODO Auto-generated method stub
		
	}



	@Override
	public void execute(L1PcInstance pc, L1ItemInstance item) {
		// TODO Auto-generated method stub
		
	}
}

